#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include "proto/robocup_ssl_client.h"
 #include <math.h>

using namespace std;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle(QString("grSim RoboCupUSM Client - v 1.0"));
    ui->Send->setDisabled(true);
    timer1 = new QTimer (this);
    timer1->setInterval(200);
    timer2 = new QTimer (this);
    timer2->setInterval(10);
    connect(ui->lineEdit_address, SIGNAL(textEdited(QString)), this, SLOT(updateaddress()));
    connect(ui->lineEdit_port, SIGNAL(textEdited(QString)), this, SLOT(updateaddress()));
    connect(ui->connect, SIGNAL(clicked()), this, SLOT(conectar()));
    connect(ui->reset, SIGNAL(clicked()), this, SLOT(reset()));
    connect(ui->Send, SIGNAL(clicked()), this, SLOT(send()));
    connect(timer1, SIGNAL(timeout()), this, SLOT(send()));
    connect(timer2, SIGNAL(timeout()), this, SLOT(recv()));
    connect(ui->Recv, SIGNAL(clicked()), this, SLOT(btnRecv()));

    client = new RoboCupSSLClient(10020,"224.5.23.2");
    /*commandSocket = new QUdpSocket(this);
    if (commandSocket->bind(QHostAddress::Any,10002))
        cout << "sockect" << endl;
    QObject::connect(commandSocket,SIGNAL(readyRead()),this,SLOT(recvActions()));*/

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::updateaddress(){

    cout << "update port or address" << endl;
    string s = ui->lineEdit_address->text().toStdString();
    if(conection.isconect()){
        conection.desconectar();
        conection.setip(s);
        conection.conectar();
        cout << "reconectado" << endl;
    }
    else conection.setip(s);
}
void MainWindow::conectar(){

    cout << "conectando..." << endl;

    if(conection.conectar()) {
            ui->Send->setDisabled(false);
            conectado = true;
            cout << "conectado" << endl;
            timer1->start();
            timer2->start();
            client->open();


    }
    else cout << "No se pudo conectar" << endl;

    theOne = Robot(conection);
}
void MainWindow::reset(){
    cout << "reset..." << endl;
    conection.desconectar();
    timer1->stop();
    timer2->stop();
    ui->Send->setDisabled(true);
    conectado = false;
    cout << "desconectado" << endl;
}

void MainWindow::send(){
}

void MainWindow::btnRecv(){

    timer2->start();
    client->open();

}


void MainWindow::recv(){

    while(!client->receive(packet)){}
    theOne.setOrientation(packet.detection().robots_yellow(0).orientation());
    theOne.setPosition(QPoint(packet.detection().robots_yellow(0).x(),packet.detection().robots_yellow(0).y()));
    theOne.followTheBall(QPoint(packet.detection().balls(0).x(),packet.detection().balls(0).y()));
   // cout << "X: " << packet.detection().balls(0).x() << endl;
   // cout << "Y: " << packet.detection().balls(0).y() << endl;

}
